# -*- coding: utf-8 -*-
"""
Created on 2024/11/27 22:19
@author: 江中新
"""

# https://www.geetest.com/demo/slide-float.html

import time
from loguru import logger
import execjs
import re
from curl_cffi import requests
from concurrent.futures import ProcessPoolExecutor


# session = requests.Session()


class GeetestSense:
    def __init__(self):
        self.ctx = None
        self.register_slide_url = None
        self.gettype_url = None
        self.challenge = None
        self.gt = None
        self.w1 = None
        self.w2 = None
        self.w3 = None
        self.aes_key = None
        self.new_challenge = None
        self.c1 = None
        self.s1 = None
        self.c = None
        self.s = None
        self.bg = None
        self.slice = None
        self.distance = None
        self.slide_track = None
        self.pass_time = None
        self.enctrack = None
        self.headers = {
            'accept': 'application/json, text/javascript, */*; q=0.01',
            'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8',
            'cache-control': 'no-cache',
            'pragma': 'no-cache',
            'priority': 'u=1, i',
            'referer': 'https://www.geetest.com/demo/slide-float.html',
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
        }

    def read_js(self):
        with open('./start.js', 'r', encoding='utf-8') as f:
            self.ctx = execjs.compile(f.read())
        logger.success("js读取成功")

    def get_w1(self):
        data = self.ctx.call('get_w1', self.gt, self.challenge)
        self.w1 = data['w']
        self.aes_key = data['aes_key']

    def get_w2(self):
        self.w2 = self.ctx.call('get_w2', self.gt, self.challenge, self.aes_key, self.c1, self.s1)

    def register_slide(self):
        self.register_slide_url = "https://demos.geetest.com/gt/register-fullpage"
        params = {
            't': str(round(time.time() * 1000))
        }
        response = requests.get(self.register_slide_url, params=params, headers=self.headers)
        self.challenge = response.json()["challenge"]
        self.gt = response.json()["gt"]
        # logger.debug("challenge: {}".format(self.challenge))
        # logger.debug("gt: {}".format(self.gt))

    def gettype(self):
        self.gettype_url = "https://apiv6.geetest.com/gettype.php"
        params = {
            'gt': self.gt,
            'callback': 'geetest_' + str(round(time.time() * 1000))
        }
        requests.get(self.gettype_url, params=params, headers=self.headers)
        # logger.info("response: {}".format(response.text))  # TODO: {"slide": 103, "click3": 128, "voice": 128, "beeline": 50}

    def get_php(self):
        """
        w1
        :return:
        """
        self.get_w1()  # self.w1
        # logger.info(f"w1: {self.w1}, len: {len(str(self.w1))}")  # 1516
        url = "https://apiv6.geetest.com/get.php"
        params = {
            "gt": self.gt,
            "challenge": self.challenge,
            "lang": "zh-cn",
            "pt": "0",
            "client_type": "web",
            "w": self.w1,
            "callback": "geetest_" + str(round(time.time() * 1000))
        }
        # time.sleep(0.5)
        response = requests.get(url, headers=self.headers, params=params)
        # print(f"get_php_response--> {response.content.decode('utf-8').encode('latin1').decode('unicode_escape')}")
        self.c1 = re.findall(r'"c": (.*?), "s', response.text)[0]
        self.s1 = re.findall(r'"s": "(.*?)", ', response.text)[0]
        # logger.debug(f"c1: {self.c1}, s1: {self.s1}")

    def ajax_php(self):
        """
        w2
        :return:
        """
        self.get_w2()  # self.w2
        # logger.info(f"w2: {self.w2}, len: {len(str(self.w2))}")  # 长度固定，看鼠标轨迹
        url = "https://api.geetest.com/ajax.php"
        params = {
            "gt": self.gt,
            "challenge": self.challenge,
            "lang": "zh-cn",
            "pt": "0",
            "client_type": "web",
            "w": self.w2,
            "callback": "geetest_" + str(round(time.time() * 1000))
        }
        time.sleep(1)
        response = requests.get(url, headers=self.headers, params=params)
        print(f"ajax_php_response--> {response.content.decode('utf-8').encode('latin1').decode('unicode_escape')}")
        if "validate" in response.text:
            logger.success(
                "验证成功, validate is {}".format(re.findall(r'"validate": "(.*)", "score"', response.text)[0]))

    def task_sequence(self):
        self.register_slide()
        self.gettype()
        self.get_php()
        self.ajax_php()

    def main(self):
        self.read_js()
        tasks = []
        with ProcessPoolExecutor(max_workers=4) as executor:
            for _ in range(100):
                tasks.append(executor.submit(self.task_sequence))

        for task in tasks:
            task.result()


if __name__ == "__main__":
    GeetestSense().main()
